package com.ruoyi.auth.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ruoyi.common.cas.CasConfiguration;
import com.ruoyi.common.cas.DefaultAjaxAuthenticationRedirectStrategy;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.core.domain.R.ok;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RedisService redisService;

    @Resource
    private CasConfiguration casConfig;

    @RequestMapping("login")
    public R<?> login(@RequestParam(value = "clientPage",required = false) String clientPage, HttpServletRequest request, HttpServletResponse response)
    {
        String userName = redisService.getCacheObject(CacheConstants.CAS_EMPLOYEE_NO);
        // 用户登录
        LoginUser userInfo = sysLoginService.login(userName);
        // 获取登录token
        Map<String, Object> map = tokenService.createToken(userInfo);
        /*response.setStatus(200);
        clientPage = org.springframework.util.StringUtils.isEmpty(clientPage) ? this.casConfig.getHomePage() : clientPage;
        response.setHeader("location", clientPage);*/
        return R.ok(map);
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) throws UnsupportedEncodingException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        HttpSession session = request.getSession();
        if (session != null) {
            session.removeAttribute("_const_cas_assertion_");
            session.invalidate();
        }
        redisService.deleteObject(CacheConstants.CAS_EMPLOYEE_NO);

        String callbackUrl = DefaultAjaxAuthenticationRedirectStrategy.getCallbackUrl(request, this.casConfig.getHomePage());
        String redirectUrl = this.casConfig.getCasServerLogoutUrl() + "?service=" + URLEncoder.encode(callbackUrl, "UTF-8");
        return R.ok(redirectUrl);
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return ok();
        }
        return ok();
    }
}
